package lucky.xiong.实际工作问题.超时控制.code;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author L-xiongjianlin
 */
public class RemoteServiceExecutor {

    public static <T> T executeWithTimeout(RemoteServiceTask<T> task, long timeout, TimeUnit unit) throws Exception {
        long startTime = System.currentTimeMillis();
        Callable<T> callable = task::execute;
        Future<T> future = Executors.newSingleThreadExecutor().submit(callable);
        try {
            T result = future.get(timeout, unit);
            long endTime = System.currentTimeMillis();
            System.out.println("调用时间: " + (endTime - startTime) + "毫秒");
            return result;
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("调用超时");
            throw e;
        } catch (ExecutionException e) {
            throw new Exception(e.getCause());
        } catch (InterruptedException e) {
            throw e;
        }
    }
}

